#include "ems_summary.h"

EMS_Summary::EMS_Summary(QWidget *parent)
    : QWidget{parent}
{
    // setupUI();
    alarm_sound=new QSoundEffect;
    alarm_sound->setVolume(1);
    alarm_sound->setSource(QUrl::fromLocalFile("./Resource/alarm.wav"));  // 或资源路径QUrl("qrc:/alarm.wav")
}

///构建UI界面
void EMS_Summary::setupUI() {
    // 主布局
    QVBoxLayout *mainLayout = new QVBoxLayout(this);

    // 顶部信息栏
    QWidget *topInfo = createTopInfoWidget();
    mainLayout->addWidget(topInfo);

    // 中间图表区
    QWidget *chartArea = createChartWidget();
    mainLayout->addWidget(chartArea, 1);

    // 底部设备状态
    QWidget *deviceStatus = createDeviceStatusWidget();
    mainLayout->addWidget(deviceStatus);

    setStyleSheet("QWidget { background: #f0f0f0; }"
                  "QLabel { font: 14px; }"
                  "QGroupBox { border: 1px solid #ccc; margin-top: 10px; }");
    setupConnections();
}

///创建顶部信息窗口
QWidget* EMS_Summary::createTopInfoWidget() {
    QWidget *widget = new QWidget;
    QGridLayout *layout = new QGridLayout(widget);

    // 关键指标
    lblTotal = createInfoLabel("今日总能耗", "0 kWh", "#2ecc71");
    lblPower = createInfoLabel("当前功率", "0 kW", "#3498db");
    lblCarbon = createInfoLabel("碳排放", "0 t", "#e74c3c");

    layout->addWidget(lblTotal, 0, 0);
    layout->addWidget(lblPower, 0, 1);
    layout->addWidget(lblCarbon, 0, 2);

    return widget;
}

///创建图标窗口
QWidget* EMS_Summary::createChartWidget() {
    QWidget *widget = new QWidget;
    QHBoxLayout *layout = new QHBoxLayout(widget);

    // 能耗趋势图
    // 24小时趋势图
    // QChartView *chartView = new QChartView;
    // chartView->setChart(createLineChart());
    // chartView->setRenderHint(QPainter::Antialiasing);
    QCustomPlot *plot=createLineChart();
    // 能耗分布图
    // 能耗分布饼状图
    // QChartView *pieChartView = new QChartView;
    // pieChartView->setChart(createPieChart());
    // pieChartView->setRenderHint(QPainter::Antialiasing);

    layout->addWidget(plot);
    // layout->addWidget(pieChartView, 1);


    return widget;
}

///创建设备的状态栏
QWidget* EMS_Summary::createDeviceStatusWidget() {
    device_status=new QList<QListWidgetItem*>;
    QGroupBox *group = new QGroupBox("设备状态");
    QHBoxLayout *layout = new QHBoxLayout(group);
    QListWidget *deviceList = new QListWidget;
    QList<Receive_Processor*> *receive_processors=this->serial_tool_widget->receive_processor_list;

    // QStringList devices;
    for(int i=0;i<receive_processors->count();i++)
    {
        // QString *head=new QString();
        QListWidgetItem *item=new QListWidgetItem("设备地址"+receive_processors->value(i)->address+": 未检测到异常");
        deviceList->addItem(item);
        device_status->push_back(item);
        // devices.append(*head);
    }

    // QStringList devices = {"HVAC系统: ✔ 正常", "照明系统: ⚠ 部分异常",
                           // "生产设备: ✔ 正常", "光伏系统: ✔ 运行中"};
    // deviceList->addItems(devices);
    deviceList->setStyleSheet("font: 12px;");

    layout->addWidget(deviceList,8);

    Warning_Light=new QLabel;
    L_green=new QPixmap("./Resource/L_green.tiff");
    L_red=new QPixmap("./Resource/L_red.tiff");
    L_gray=new QPixmap("./Resource/L_gray.tiff");
    L_yellow=new QPixmap("./Resource/L_yellow.tiff");
    Warning_Light->setPixmap(*L_gray);
    Warning_Light->setScaledContents(true);
    layout->addWidget(Warning_Light,2);
    return group;
}

///创建线性图表
QCustomPlot* EMS_Summary::createLineChart() {
    DatabaseManager &instance=DatabaseManager::instance();
    //​SQLite按小时聚合查询
    QString sql_str="SELECT strftime('%H', Recorded_Time) AS hour,SUM(Active_Power_ALL) AS total_power FROM \"01\""
                      "WHERE DATE(Recorded_Time) = '2025-5-1' GROUP BY hour ORDER BY hour";
    QVector<double> hours(24), powerValues(24);


    //处理查询结果
    QSqlQuery *query=instance.executeQuery(sql_str);
    while (query->next()) {
        int hour = query->value("hour").toInt();
        powerValues[hour] = query->value("total_power").toDouble();
    }
    // 填充缺失小时为0
    for (int i=0; i<24; ++i) hours[i] = i;
    // QCustomPlot图表配置
    QCustomPlot *plot = new QCustomPlot(this);
    plot->addGraph();
    plot->graph(0)->setData(hours, powerValues);

    //​坐标轴与样式设置
    // X轴（小时）
    plot->xAxis->setLabel("时间（小时）");
    plot->xAxis->setRange(0, 23);
    plot->xAxis->setTickLengthIn(2);  // 每2小时一个刻度

    // Y轴（功率）
    plot->yAxis->setLabel("能耗（kW·h）");
    plot->yAxis->setRange(0, *std::max_element(powerValues.begin(), powerValues.end())*1.1);

    // 曲线样式
    plot->graph(0)->setPen(QPen(Qt::blue, 2));
    plot->graph(0)->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, 6));

    plot->setInteractions(QCP::iRangeZoom | QCP::iRangeDrag);  // 支持缩放拖拽
    plot->legend->setVisible(true);  // 显示图例

    return plot;
}

///创建圆饼状图表
// QCustomPlot* EMS_Summary::createPieChart() {

    // QChart *chart = new QChart;
    // QPieSeries *series = new QPieSeries;
    // QLegend *legend=chart->legend();
    // legend->setLabelBrush(QBrush(Qt::white)); // 设置标签为白色
    // series->append("生产设备", 55);
    // series->append("HVAC", 25);
    // series->append("照明", 15);
    // series->append("其他", 5);
    // chart->addSeries(series);
    // chart->setTitle("能耗分布");
    // chart->setBackgroundBrush(QBrush(QColor("#2c3e50")));
    // chart->setTitleBrush(Qt::white);

    // return plot;
// }

///创建特殊的QLabel标签
QLabel* EMS_Summary::createInfoLabel(const QString &title, const QString &value, const QString &color) {
    QLabel *label = new QLabel;
    label->setAlignment(Qt::AlignCenter);//居中处理
    label->setStyleSheet(QString(
                             "QLabel {"
                             "  background: %1;"
                             "  border-radius: 10px;"
                             "  padding: 15px;"
                             "  color: white;"
                             "  font: bold 16px;"
                             "}").arg(color));

    label->setText(QString("<b>%1</b><br>%2").arg(title, value));
    return label;
}

///设置数据
//由于要进行统计性的数据计算，故不能在每次串口接受到数据时都进行调用，这样会十分占用性能
//因此对于数据面板的计算应该单独设置计时器进行触发计算
//其应该能够读取数据库数据，以及配置文件的一些属性，这可以在构造函数中进行直接配置，有需要的话则可另设函数对配置属性进行刷新
void EMS_Summary::update_current_active_power() {
    //根据数据库和数据处理器来进行周期性的数据统计
    DatabaseManager &instance=DatabaseManager::instance();
    /*
    // chart_Line->removeAllSeries();
    // for(int device_index=0;device_index<this->serial_tool_widget->receive_processor_list->count();device_index++)
    // {

    //     // QString table_name;
    //     // table_name+="\""+this->serial_tool_widget->receive_processor_list->value(device_index)->address;
    //     // QString sql="SELECT Recorded_Time FROM "+table_name+"ORDER BY Recorded_Time DESC LIMIT 1";
    //     // qDebug()<<sql;
    //     QString sql="SELECT Recorded_Time FROM \"01\" ORDER BY Recorded_Time DESC LIMIT 1";
    //     QSqlQuery *query=instance.executeQuery(sql);
    //     QString latestTime;
    //     if (query->next()) {
    //         latestTime = query->value("Recorded_Time").toString();
    //         // qDebug()<<query->value("Recorded_Time").toString();
    //     } else {
    //         qDebug() << "未找到最新的记录";
    //         return;
    //     }

    //     // 2. 计算时间范围
    //     QDateTime endTime = QDateTime::fromString(latestTime, "yyyy-MM-dd HH:mm:ss");
    //     QDateTime startTime=endTime;
    //     series=new QLineSeries;

    //     for(int i=0;i<24*60*60;i++)
    //     {
    //         endTime=startTime;
    //         //获取向前一小时的时间
    //         startTime = startTime.addSecs(-1); // 减去1小时
    //         QString time_forward=startTime.toString("yyyy-MM-dd HH:mm:ss");
    //         time_forward='\"'+time_forward;
    //         time_forward+='\"';
    //         QString time_end=endTime.toString("yyyy-MM-dd HH:mm:ss");
    //         time_end='\"'+time_end;
    //         time_end+='\"';

    //         // qD      // qDebug()<<"返回结果"<<query_range->value(0).toDouble();
    //             total += value;
    //             count++;
    //         }
    //         if(count!=0)
    //         {
    //             //这一个小时有有效数据
    //             double result=total*0.000000278;
    //             result=abs(result);
    //             series->append(23-i,result);
    //             // qDebug()<<"x:"<<23-i<<"  "<<"y:"<<result;
    //         }
    //         // axisY->setRange(0,temp_max);
    //         // series->attachAxis(axisX);
    //         // series->attachAxis(axisY);
    //         // chart_Line->addSeries(series);
    //     }
    //     chart_Line->addSeries(series);ebug()<<"起始时间"<<time_forward;
    //         // qDebug()<<"结束时间"<<time_end;
    //         double total=0.0;
    //         QSqlQuery *query_range;
    //         QString select_range="SELECT Active_Power_ALL FROM \"01\" WHERE Recorded_Time BETWEEN "+time_forward+" AND "+time_end;
    //         query_range=instance.executeQuery(select_range);
    //         // qDebug()<<"返回结果"<<query_range->value("Apparent_Power_ALL");
    //         // 4. 累加结果
    //         double count=0;
    //         while (query_range->next()) {
    //             // bool ok;
    //             double value = query_range->value(0).toDouble();
    //
    */

    //尝试匹配当前能耗
    QDateTime current_time=QDateTime::currentDateTime();
    QDateTime diff=current_time.addSecs(-1);//一秒前记录的数据
    QString time_now=current_time.toString("yyyy-MM-dd HH:mm:ss");
    QString time_diff=diff.toString("yyyy-MM-dd HH:mm:ss");

    // qDebug()<<"开始时间 "<<time_diff;
    // qDebug()<<"结束时间"<<time_now;
    time_diff='\"'+time_diff;
    time_diff+='\"';
    time_now='\"'+time_now;
    time_now+='\"';
    QString select_sql="SELECT Active_Power_ALL FROM \"01\" WHERE Recorded_Time BETWEEN "+time_diff+" AND "+time_now;
    QSqlQuery * query_now=instance.executeQuery(select_sql);
    double value=0;
    while(query_now->next())
    {
        value = query_now->value(0).toDouble();
        value=abs(value);
        // qDebug()<<"输出值:"<<value;
    }
    QString d3 = QString::number(value * 0.001, 'f', 2);
    lblPower->setText(QString("<b>%1</b><br>%2").arg("当前功率", d3+" KW"));


    //更新状态栏信息
    bool warning=false;
    // bool connecting=false;
    for(int index=0;index<this->device_monitor->param_out_of_setting->count();index++)
    {
        for(int param_index=0;param_index<this->device_monitor->param_out_of_setting->value(index)->count();param_index++)
        {
            //
            if(this->device_monitor->param_out_of_setting->value(index)->value(param_index))
            {
                warning=true;
                this->device_status->value(index)->setText("设备地址"
                    +this->serial_tool_widget->receive_processor_list->value(index)->address+": ⚠检测到异常");
            }

            // if(this->serial_tool_widget->receive_processor_list->value(index)->real_value_list->value(param_index)!=)
        }

    }
    if(warning)
    {
        if(!alarm_sound->isPlaying())
        {
            alarm_sound->play();
        }

        this->Warning_Light->setPixmap(*L_red);
    }
    else
    {
        this->Warning_Light->setPixmap(*L_green);
    }


}


/// 今日数据
void EMS_Summary::update_today_active_power()
{
    DatabaseManager &instance=DatabaseManager::instance();

    // 构建今日时间范围（SQLite日期函数需确保时间格式正确）
    QString todayStart = QDateTime::currentDateTime().toString("yyyy-MM-dd 00:00:00");
    QString todayEnd = QDateTime::currentDateTime().toString("yyyy-MM-dd 23:59:59");
    // 执行查询（参数化查询防止SQL注入）
    QSqlQuery *query;
    // QString sql_str="SELECT Active_Power_ALL FROM \"01\" WHERE Recorded_Time BETWEEN "+time_diff+" AND "+time_now;
    QString sql_str="SELECT SUM(Active_Power_ALL) FROM \"01\" WHERE Recorded_Time BETWEEN \""+todayStart+"\" AND \""+todayEnd+"\"";
    // qDebug()<<sql_str;
    query=instance.executeQuery(sql_str);
    if(query->next()) {
        // bool ok;
        double value = query->value(0).toDouble();
        // qDebug()<<"返回结果"<<query_range->value(0).toDouble();
        value*=0.0000000556;
        QString d=QString::number(value,'f',4);//今日总能耗
        QString d2=QString::number(value*0.785,'f',4);//碳排放
        lblTotal->setText(QString("<b>%1</b><br>%2").arg("今日总能耗", d+QString(" KWH")));
        lblCarbon->setText(QString("<b>%1</b><br>%2").arg("碳排放", d2+QString(" t")));
    }
    else {
        qDebug() << "无当日数据";
    }


}
/// 24小时数据折线图更新
void EMS_Summary::update_line_chart()
{
    //根据数据库和数据处理器来进行周期性的数据统计
    DatabaseManager &instance=DatabaseManager::instance();
    chart_Line->removeAllSeries();
    // 2. 计算时间范围
    QDateTime endTime = QDateTime::currentDateTime();
    QDateTime startTime=endTime;
    chart_Line = new QChart;
    series=new QLineSeries;

    QValueAxis *axisX = new QValueAxis();
    axisX->setRange(0,24);
    axisX->setTitleText("时间/时");
    QValueAxis *axisY = new QValueAxis();
    // axisY->setRange(0,max);
    axisX->setTitleText("总能耗/KWH");
    series->attachAxis(axisX);
    series->attachAxis(axisY);
    chart_Line->addSeries(series);
    chart_Line->addAxis(axisX, Qt::AlignBottom);
    chart_Line->addAxis(axisY, Qt::AlignLeft);



}

///设置信号槽连接
void EMS_Summary::setupConnections() {
    //数据更新
    current_ap_timer = new QTimer(this);
    current_ap_timer->start(1000);
    connect(current_ap_timer, SIGNAL(timeout()), this,SLOT(update_current_active_power()));

    todays_ap_timer=new QTimer(this);
    todays_ap_timer->start(5000);
    connect(todays_ap_timer, SIGNAL(timeout()), this,SLOT(update_today_active_power()));

    line_chart_ap_timer=new QTimer(this);
    // line_chart_ap_timer->start(5000);
    connect(line_chart_ap_timer, SIGNAL(timeout()), this,SLOT(update_line_chart()));

}

